#include <stdio.h>
#include <stdlib.h>
#include "syscall.h"

//Default Port Number
#define PORT 15

//Length of messages sent;
#define TEXTLENGTH 255

//File Descriptors
#define STDIN 0
#define STDOUT 1

int main(int argc, char** argv){
    //** VARIABLES **//
    //Connection Variables
    int socket;
    int host;
    
    //Read/Write Variables
    int bytesRead;
    int bytesWritten;
    
    //Input Variables
    char input[TEXTLENGTH];
    int  posInput=0; //Position of the input
    
    //Output Variables
    char output[TEXTLENGTH];
    int  posOutput=0;
    
    //Check number of arguments
    if(argc!=2){
        printf("Error: Not enough or too few arguments.");
        return 1;
    }
    
    //**CONNECTING**//
    host=atoi(argv[1]);                 //Convert string argv to int
    socket=connect(host, PORT);         //Attempt to connect
    if(socket==-1){                     //Could not connected! Failed, terminate.
        printf("Error: Could not connect.");
        return 1;
    }
    
    while(1==1){
        //**READ FROM SERVER**//
        bytesRead=read(socket,&input[posInput],1);
        if(bytesRead!=-1){//No error code
            if('\n'==input[posInput]){
                //Display it to our console!
                bytesWritten=write(STDOUT,input,posInput);
                //Error Checking
                if(bytesWritten!=posInput) printf("Error: The entire string was not written.");
                if(bytesWritten==-1)printf("Error: Error with parameters, length of string, etc");

                posInput=0;
            }else{
                posInput++;
            }
        }
        //**READ FROM STDIN**//
        bytesRead=read(STDIN,&output[posOutput],1);
        if(bytesRead!=-1){//No error code
            //Checks to see if the string contained is ".". If it is, terminate loop;     
            if(output[0]=='.'&&output[1]=='\n'&&posOutput==2) break;
            if('\n'==output[posOutput]){
                //Submit contents to the server
                bytesWritten=write(socket,output,posOutput);
                //Error Checking
                if(bytesWritten!=posOutput) printf("Error: The entire string was not written.");
                if(bytesWritten==-1)printf("Error: Error with parameters, length of string, etc");
                
                //Display it to our console!
                bytesWritten=write(STDOUT,output,posOutput);
                //Error Checking
                if(bytesWritten!=posOutput) printf("Error: The entire string was not written.");
                if(bytesWritten==-1)printf("Error: Error with parameters, length of string, etc");
                
                posOutput=0;
            }else{
                posOutput++;
            }
        }
    }
    
    if(close(socket)==-1){
        printf("Unable to close connection");
        return 1;
    }
    return 0;
}